package com.application.lucky.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.lucky.Lucky;
import com.application.lucky.R;
import com.application.lucky.bean.UserBean;
import com.application.lucky.bean.eventbean.FriendEvent;
import com.application.lucky.config.Config;
import com.application.lucky.manager.ContactsManager;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.FriendRequest;
import com.application.lucky.request.UserRequest;
import com.application.lucky.request.nav.UrlManager;
import com.application.lucky.utils.Flog;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.dialog.TwoButtonDialog;
import com.application.mylibrary.base.BaseActivity;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.ISharedPreKey;
import com.application.mylibrary.utils.SharedPreferencesUtil;
import com.application.mylibrary.utils.ToastUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.bumptech.glide.Glide;
import com.lcw.library.imagepicker.ImagePicker;
import com.lcw.library.imagepicker.utils.ImageLoader;
import com.qunar.im.ui.util.ProfileUtils;
import com.qunar.im.utils.ConnectionUtil;
import com.qunar.im.utils.IMPreferencesUtil;
import com.suke.widget.SwitchButton;

import java.io.File;
import java.util.List;

public class UserCenterActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "UserCenterActivity";

    private static final int REQUEST_SELECT_IMAGES_CODE = 11;
    private TitlebarView mTitleBar;
    private TextView mTvUserName;
    private TextView mTvUserRemark;
    private TextView mTvUserName1;
    private TextView mTvUserId;
    private ImageView mIvHeadView;
    private TextView mTvDeleteFriend;
    private String id;
    private String uname;
    private View layout_bottom;
    private View v_bottom_line;
    private SwitchButton sb_fireafterread;
    private View layout_bottom_2;
    private View v_bottom_line_2;
    private SwitchButton sb_black;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initListener();
        loadData();
    }

    private void loadData() {
        if (TextUtils.isEmpty(id)) {
            v_bottom_line.setVisibility(View.INVISIBLE);
//            layout_bottom.setVisibility(View.GONE);
//            v_bottom_line_2.setVisibility(View.GONE);
            layout_bottom_2.setVisibility(View.GONE);

            new UserRequest().getSelfData(new CallBackEx<BaseResponse<UserBean>>() {
                @Override
                public void onSuccess(BaseResponse<UserBean> userBeanBaseResponse) {
                    if (userBeanBaseResponse.dataInfo != null) {
                        setUi(userBeanBaseResponse.dataInfo);
                    }
                }

                @Override
                public void onFailed(int code) {

                }
            });
        } else {
            v_bottom_line.setVisibility(View.VISIBLE);
//            layout_bottom.setVisibility(View.VISIBLE);
//            v_bottom_line_2.setVisibility(View.VISIBLE);

            layout_bottom_2.setVisibility(View.VISIBLE);

            new UserRequest().user_info(id, new CallBackEx<BaseResponse<UserBean>>() {
                @Override
                public void onFailed(int code) {

                }

                @Override
                public void onSuccess(BaseResponse<UserBean> userBeanBaseResponse) {
                    if (userBeanBaseResponse.dataInfo != null) {
                        setUi(userBeanBaseResponse.dataInfo);
                    }
                }
            });
        }

    }

    private void initListener() {
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finishAnim();
            }

            @Override
            public void rightClick() {

            }
        });
        mTvDeleteFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new TwoButtonDialog.Build(UserCenterActivity.this)
                        .setMessage(R.string.chat_delete_friend)
                        .setLeftButton("取消", null)
                        .setRightButton("确定", new TwoButtonDialog.BaseDialogClickListener() {
                            @Override
                            public void click() {
                                new FriendRequest().friend_delete(id, new CallBackEx<BaseResponse<String>>() {
                                    @Override
                                    public void onFailed(int code) {
                                        ToastUtils.show("删除失败");
                                    }

                                    @Override
                                    public void onSuccess(BaseResponse<String> stringBaseResponse) {
                                        EventBusUtils.post(new FriendEvent());
                                        String imUid = Config.IMIdUtils.getIMUid(id);
                                        ConnectionUtil.getInstance().deleteCoversationAndMessage(imUid, imUid);
                                        setResult(1);

                                        SharedPreferencesUtil.remove(Lucky.getApplication(), ISharedPreKey.KEY_FIREAFTERREAD_CHECK + id);
                                        SharedPreferencesUtil.remove(Lucky.getApplication(), IMPreferencesUtil.PreferencesKey.KEY_BLACK_CHECK + id);
                                        finishAnim();
                                    }
                                });
                            }
                        }).create().show();
                ;

            }
        });

        sb_fireafterread.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                String key = ISharedPreKey.KEY_FIREAFTERREAD_CHECK + id;
                SharedPreferencesUtil.saveBoolean(Lucky.getApplication(), key, isChecked);
            }
        });

        sb_black.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                IMPreferencesUtil.saveBoolean(Lucky.getApplication(), IMPreferencesUtil.PreferencesKey.KEY_BLACK_CHECK + id, isChecked);
            }
        });
    }

    public void setUi(UserBean dataInfo) {
        mTvUserName.setText(dataInfo.getShowName());
        mTvUserName1.setText(dataInfo.getNickName());
        mTvUserRemark.setText("");
        setUid(dataInfo.getUserId() + "");

        ProfileUtils.displayGravatarByImageSrc(UserCenterActivity.this, UrlManager.getHeadPic(dataInfo.getHeadPic()), mIvHeadView);
    }

    private void setUid(String uid) {
        try {
            Long integer = Long.valueOf(uid);
            mTvUserId.setText(""+(integer ^ Config.ID_proguard));
        } catch (Exception e) {
            mTvUserId.setText(uid);
        }
    }

    private void initView() {
        mTitleBar = (TitlebarView) findViewById(R.id.title_bar);
        mTvUserName = (TextView) findViewById(R.id.tv_user_name);
        mTvUserRemark = (TextView) findViewById(R.id.tv_user_remark);
        mTvUserName1 = (TextView) findViewById(R.id.tv_user_name1);
        mTvUserId = (TextView) findViewById(R.id.tv_user_id);
        mIvHeadView = (ImageView) findViewById(R.id.iv_head_view);
        mTvDeleteFriend = (TextView) findViewById(R.id.tv_delete_friend);
        layout_bottom = findViewById(R.id.layout_bottom);
        v_bottom_line = findViewById(R.id.v_bottom_line);
        sb_fireafterread = (SwitchButton) findViewById(R.id.sb_fireafterread);

        layout_bottom_2 = findViewById(R.id.layout_bottom_2);
        v_bottom_line_2 = findViewById(R.id.v_bottom_line_2);
        sb_black = (SwitchButton) findViewById(R.id.sb_black);

        if (SharedPreferencesUtil.getBoolean(Lucky.getApplication(), ISharedPreKey.KEY_FIREAFTERREAD_CHECK + id, false)) {
            sb_fireafterread.setChecked(true);
        }

        if (IMPreferencesUtil.getBoolean(Lucky.getApplication(), IMPreferencesUtil.PreferencesKey.KEY_BLACK_CHECK + id, false)) {
            sb_black.setChecked(true);
        }

        if (ContactsManager.getInstance().isFriend(id)) {
            mTvDeleteFriend.setVisibility(View.VISIBLE);
        }

//        mIvHeadView.setOnClickListener(this);
        mTvUserName.setOnClickListener(this);
    }

    @Override
    public void beforeInit() {
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        uname = intent.getStringExtra("uname");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_center;
    }

    public static void jump(Context context, String id, String uname) {
        Intent intent = new Intent(context, UserCenterActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("uname", uname);
        context.startActivity(intent);
    }

    public static void jumpForResult(Context context, String id, String uname) {
        Intent intent = new Intent(context, UserCenterActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("uname", uname);
        if (context instanceof Activity) {
            ((Activity) context).startActivityForResult(intent, 999);
        }

    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_user_name || viewId == R.id.iv_head_view) {
            if (!TextUtils.isEmpty(id)) {
                return;
            }

            ImagePicker.getInstance()
                    .setTitle(getString(R.string.profile_head))//设置标题
                    .showCamera(true)//设置是否显示拍照按钮
                    .showImage(true)//设置是否展示图片
                    .showVideo(false)//设置是否展示视频
                    .setSingleType(true)//设置图片视频不能同时选择
                    .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
//                    .setImagePaths(mImageList)//保存上一次选择图片的状态，如果不需要可以忽略
                    .setImageLoader(new GlideLoader())//设置自定义图片加载器
                    .start(UserCenterActivity.this, REQUEST_SELECT_IMAGES_CODE);

        }
    }

    private byte[] headByte;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            final List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            Flog.d(TAG, "onActivityResult imagePaths:" + imagePaths);
            if (imagePaths != null && !imagePaths.isEmpty()) {
                showloadDialog();

                Flog.d(TAG, "filePath:"+imagePaths.get(0));
                new UserRequest().updateHeadPic(imagePaths.get(0), new CallBackEx<BaseResponse<String>>(){
                    @Override
                    public void onSuccess(BaseResponse<String> baseResponse) {
                        Flog.d(TAG, "updateHeadPic onSuccess baseResponse:"+baseResponse);
                    }

                    @Override
                    public void onFailed(int code) {
                        Flog.d(TAG, "updateHeadPic onFailed code:"+code);
                    }
                });

                // TODO 等待服务器接口
                Glide.with(getApplicationContext()).load(Uri.fromFile(new File(imagePaths.get(0)))).into(mIvHeadView);
                hideLoadDialog();
            }
        }
    }

    class GlideLoader implements ImageLoader {

        @Override
        public void loadImage(ImageView imageView, String imagePath) {
            //小图加载
            Glide.with(imageView.getContext()).load(imagePath).centerCrop().into(imageView);
        }

        @Override
        public void loadPreImage(ImageView imageView, String imagePath) {
            //大图加载
            Glide.with(imageView.getContext()).load(imagePath).centerCrop().into(imageView);

        }

        @Override
        public void clearMemoryCache() {
            //清理缓存
            Glide.get(Lucky.getApplication()).clearMemory();
        }
    }
}
